import type { DirectiveBinding, ObjectDirective } from "vue";

const drag: ObjectDirective = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { el: handle, boundarycall } = binding.value; // 获取拖动区域的选择器，默认为'.topbar'
    console.log(binding);

    // 在指令绑定时执行的操作
    let offsetX: number = 0;
    let offsetY: number = 0;
    let isMove = false;

    let target: HTMLElement | null = handle ? el.querySelector(handle) : el; // 获取拖动区域的DOM元素
    // console.log(target);

    if (!target) {
      throw new Error(`Can't find handle: ${handle} in element.`);
    }

    el.addEventListener("mousedown", (e: MouseEvent) => {
      // console.log(e.target, target);

      if (handle && e.target !== target) return;
      isMove = true;
      console.log(isMove);

      offsetX = e.clientX - el.offsetLeft;
      offsetY = e.clientY - el.offsetTop;
    });

    document.addEventListener("mousemove", (e: MouseEvent) => {
      // if (isMove)
      if (!isMove && !!handle && e.target !== target) return;

      if (e.clientX <= 0 || e.clientY <= 0) {
        boundarycall({
          x: e.clientX,
          y: e.clientY,
          type: "keydownBefore",
        });
      }

      if (offsetX !== 0 || offsetY !== 0) {
        el.style.top = `${e.clientY - offsetY}px`;
        el.style.left = `${e.clientX - offsetX}px`;
      }
    });

    document.addEventListener("mouseup", (e) => {
      isMove = false;

      // if (e.target !== handle) return
      if (e.clientX <= 0 || e.clientY <= 0) {
        boundarycall({
          x: e.clientX,
          y: e.clientY,
          type: "keydownAfter",
        });
      }
      offsetX = 0;
      offsetY = 0;
    });
  },
};

export default drag;
